<?php
/**
 * 查询code状态，非正常无法提交订单
 */
require_once ('common.php');

$get_code_url = 'https://api.weixin.qq.com/card/code/get?access_token='; //查看code状态地
$access_token = get_access_token();

//接收数据
$data = $_GET;
if(empty($data)){
    echo_Json(-1, '数据不能为空');
}
$card_id = trim($data['card_id']);
$code    = trim($data['code']);
if(empty($card_id)){
    echo_Json(-1, '卡券card_id不能为空');
}
if(empty($code)){
    echo_Json(-1, '卡券code码不能为空');
}
/*--------------------查询code接口，验证卡券当前是否可用状态 start--------------------------*/
$postcodeData = array(
    'card_id' => $card_id,
    'code'    => $code,        //正常状态的code
    'check_consume' => false   //校验code核销状态,填true和false返回结果不同，在这使用false
);

$cardcodestatus = getcodeStatus($get_code_url.$access_token, $postcodeData);
if($cardcodestatus == 0){
    //卡券状态正常，可以核销
    echo_Json(0, '卡券状态正常，可以核销');
}elseif($cardcodestatus == 1){
    echo_Json(1, '卡券已核销,无法核销');
}elseif($cardcodestatus == 2){
    echo_Json(2, '卡券已过期，无法核销');
}elseif($cardcodestatus == 3){
    echo_Json(3, '卡券转赠中，无法核销');
}elseif($cardcodestatus == 4){
    echo_Json(4, '卡券转赠超时，无法核销');
}elseif($cardcodestatus == 5){
    echo_Json(5, '卡券已删除，无法核销');
}elseif($cardcodestatus == 6){
    echo_Json(6, '卡券已失效，无法核销');
}elseif($cardcodestatus == 7){
    echo_Json(7, '卡券状态未知，无法核销');
}else{
    echo_Json($cardcodestatus, '获取卡券状态失败');
}

//获取卡券当前状态
function getcodeStatus($url, $data){
    $result = jsonpostJson($url, $data, true);
    if($result['errcode'] == 0){
        //接口正常，再判断卡券状态
        switch($result['user_card_status']){
            case 'NORMAL':    //正常
                $status = 0;
                break;
            case 'CONSUMED':  //已核销
                $status = 1;
                break;
            case 'EXPIRE':    //已过期
                $status = 2;
                break;
            case 'GIFTING':   //转赠中
                $status = 3;
                break;
            case 'GIFT_TIMEOUT': //转赠超时
                $status = 4;
                break;
            case 'DELETE':   //已删除
                $status = 5;
                break;
            case 'UNAVAILABLE': //已失效
                $status = 6;
                break;
            default:
                $status = 7;  //卡券状态未知
                break;
        }
    }else{
        //接口报错
        $status = $result['errcode'];
    }
    return $status;
}